package com.ego.auth.controller;

import com.ego.auth.client.UserClient;
import com.ego.auth.entity.UserInfo;
import com.ego.auth.properties.JwtProperties;
import com.ego.auth.service.AuthService;
import com.ego.auth.utils.CookieUtils;
import com.ego.auth.utils.JwtUtils;
import com.ego.exception.EgoException;
import com.ego.exception.ExceptionEnum;
import com.ego.user.pojo.User;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Ares
 * @date 2020-12-8
 */
@RestController
@EnableConfigurationProperties(JwtProperties.class)
@Slf4j
public class AuthController {

    @Resource
    private AuthService authService;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private UserClient userClient;

    /**
     * 登录授权
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response) {
        System.out.println("1111111");
        try{
            //1.判断用户名密码是否正确
            User user = userClient.queryUser(username, password);
            //2.创建jwt
            String token = JwtUtils.generateToken(new UserInfo(user.getId(), user.getUsername()), jwtProperties.getPrivateKey(), 5);
            //3.将jwt写入cookie
            CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getExpire()*60);
            return ResponseEntity.ok().build();
        }catch (FeignException.BadRequest e){
            log.error("用户名密码错误",e);
            throw new EgoException(ExceptionEnum.USERNAME_OR_PASSWORD_ERROR);
        } catch (Exception e) {
            log.error("创建jwt token错误",e);
            throw new EgoException(ExceptionEnum.JWT_CREATE_ERROR);
        }
    }
    /**
     * 验证用户信息
     * @param token
     * @return
     */
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verify(@CookieValue(value = "EGO_TOKEN",required = false) String token) {
        UserInfo userInfo = null;
        try {
            userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        return ResponseEntity.ok(userInfo);
    }
}
